package org.example.pims.security.service;


import org.example.commons.entity.SysRole;
import org.example.commons.entity.SysUser;
import org.example.commons.enums.AccountStatusEnum;
import org.example.pims.security.LoginUser;
import org.example.pims.security.utils.StringUtils;
import org.example.commons.exception.CustomException;
import org.example.commons.service.ISysRoleService;
import org.example.commons.service.ISysUserRoleService;
import org.example.user.manage.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 住户 用户验证处理
 */
@Service
public class UserUserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserUserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.findByPhone(username);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        if (AccountStatusEnum.DISABLED.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new CustomException("对不起，您的账号：" + username + " 已停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user) {
        //查找adminId = 0 的角色作为住户的角色
        List<SysRole> roles = sysUserRoleService.findRoleByAdminId(0L);
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (SysRole role : roles) {
            authorities.add(new CustomGrantedAuthority("ROLE_" + role.getRoleKey().toUpperCase()));
        }

        return new LoginUser(user.getPhone(),user.getPassword(),authorities,null,user);
    }
}
